package com.example.enews

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.enews.databinding.ActivityMainBinding
import com.example.enews.adapters.NewsAdapter
import com.example.enews.fragments.DataFragment
import com.example.enews.fragments.MatchFragment
import com.example.enews.fragments.NewsFragment
import com.example.enews.viewmodels.NewsViewModel

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: NewsViewModel
    private val adapter = NewsAdapter { /* 点击事件处理 */ }
    private val newsFragment = NewsFragment()
    private val matchFragment = MatchFragment()
    private val dataFragment = DataFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化默认显示首页
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container2, newsFragment)
                .commitNow()
        }
        // 移除不必要的 RecyclerView 设置
        // setupRecyclerView()
        setupViewModel()
        observeData()
        setupBottomNavigation()
    }

    private fun setupViewModel() {
        viewModel = ViewModelProvider(this)[NewsViewModel::class.java]
    }

    private fun observeData() {
        viewModel.newsList.observe(this) { newsList ->
            adapter.submitList(newsList)
            binding.placeholder.text = if (newsList.isEmpty()) getString(com.example.enews.R.string.no_news) else ""
        }
    }

    private fun setupBottomNavigation() {
        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when(item.itemId) {
                R.id.nav_news -> showFragment(newsFragment)
                R.id.nav_match -> showFragment(matchFragment)
                R.id.nav_data -> showFragment(dataFragment)
            }
            true
        }
    }

    private var currentFragment: Fragment = newsFragment

    private fun showFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()

        // 如果要显示的Fragment还没有添加到Activity中
        if (!fragment.isAdded) {
            transaction.add(R.id.container2, fragment)
        }

        // 隐藏当前Fragment，显示目标Fragment
        transaction.hide(currentFragment).show(fragment)
        currentFragment = fragment

        transaction.commit()
    }
}